const webpack = require('webpack')
const path = require('path')
const glob = require('glob')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const autoprefixer = require('autoprefixer')
const HtmlWebpackPlugin = require('html-webpack-plugin')
//静态资源输出
const copyWebpackPlugin = require("copy-webpack-plugin");
const hostIp = require('./IP')()
function getEntry () {
    const entry = {}
    glob.sync('./src/js/*.js').map(file => {
        let start = file.indexOf('src/') + 4;
        let end = file.length - 3;
        let index = file.substring(start, end)
        index = index.split('/')[1];
        entry[index] = file
    })
    return entry;
}

function getHtmlTemplates () {
    let entry = getEntry();
    let htmlTemplate = []
    Object.keys(entry).forEach(index => {
        htmlTemplate.push(new HtmlWebpackPlugin({
            template: `src/pages/${index}.html`,
            filename: `${index}.html`,
            chunks: ['vendor', index] // 默认会将打包出的所有 js 插入 html。故需指明页面需要的模块
        }))
    })
    return htmlTemplate;
}

let htmlTemplate = getHtmlTemplates()
module.exports = {
    entry: getEntry(),
    output: {
        filename: "js/[name].js",
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env']
                    }
                }
            },
            {
                test: /\.css$/,
                //use:['style-loader','css-loader','postcss-loader']//css不分离写法
                //css分离写法
                use: [MiniCssExtractPlugin.loader, "css-loader", {
                    loader: "postcss-loader",
                    options: {
                        plugins: [
                            autoprefixer({
                                browsers: ['ie >= 8', 'Firefox >= 20', 'Safari >= 5', 'Android >= 4', 'Ios >= 6', 'last 4 version']
                            })
                        ]
                    }
                }]
            },
            {
                test: /\.(png|jpg|gif|jpeg)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 5000,
                            outputPath: "./images",//打包后图片文件输出路径
                            publicPath: '/images'
                        }
                    }
                ]
            },
            { //页面中会用到img标签，img引用的图片地址也需要一个loader来处理,这样再打包后的html文件下img就可以正常引用图片路径了
                test: /\.(htm|html)$/,
                use: 'html-withimg-loader'
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: ["file-loader"]
            }
        ]
    },
    // 提取公共代码
    optimization: {
        splitChunks: {
            cacheGroups: {
                vendor: {   // 抽离第三方插件
                    test: /node_modules/,   // 指定是node_modules下的第三方包
                    chunks: 'initial',
                    name: 'vendor',  // 打包后的文件名，任意命名
                    // 设置优先级，防止和自定义的公共代码提取时被覆盖，不进行打包
                    priority: 10
                }
            }
        }
    },
    plugins: [
        //将css分离出去
        new MiniCssExtractPlugin({
            filename: "css/[name].css"
        }),
        new webpack.ProvidePlugin({//全局引入jquery
            $: "jquery",
            jQuery: "jquery",
            jquery: "jquery",
            "window.jQuery": "jquery"
        }),
        //静态资源输出
        new copyWebpackPlugin([{
            from: path.resolve(__dirname, "./src/assets"),
            to: './assets',
            ignore: ['.*']
        }]),
        ...htmlTemplate
    ],
    devServer: {
        hot: true,
        host:hostIp,
        port: '8089',
        open: false
    }
}
